<template>
  <div class="detail">
    <book-info :book="bookInfo" v-if="readyFor"></book-info>

    <comment-list :comments="comments" v-if="readyFor"></comment-list>

    <div class="comments" v-if="showAddComment">
      <textarea 
        v-model="comment"
        class="textarea"
        maxlength="100"
        placeholder="请输入图书评论短评"
      ></textarea>
      <div class="location">
        地理位置：
        <switch color="#ea5a49" name="location" :checked="location" @change="getGeo"></switch>
        <span>{{location}}</span>
      </div>
      <div class="phone">
        手机型号：
        <switch color="#ea5a49" name="phone" :checked="phone" @change="getPhone"></switch>
        <span>{{phone}}</span>
      </div>

      <button class="btn" @click="addComment">提交</button>
    </div>
    <div v-else class="text-footer">
      {{commentMsg}}
    </div>
    <button class="btn" open-type="share">转发给好友</button>
  </div>
</template>

<script>
import BookInfo from '@/components/BookInfo.vue'
import CommentList from '@/components/CommentList.vue'
import {showMod} from '@/utils/index'

const db = wx.cloud.database()
export default {
  name: 'Detail',
  data () {
    return {
      bookId: '', // 当前书的id
      userinfo: {}, // 当前登录的用户信息
      bookInfo: {}, // 当前书籍信息
      readyFor: false, // v-if解决父子组件传值的问题
      comment: '', // 输入的评论内容
      location: '', // 用户地理位置
      phone: '', // 手机型号
      comments: [], // 评论列表
      commentMsg: '' // 评论框不显示是的提示信息
    }
  },
  computed: {
    showAddComment () {
      // 没登录
      if (!this.userinfo._openid) {
        this.commentMsg = '登陆后才能评论噢😋'
        return false
      }
      // 已经添加了评论
      if (this.comments.filter(v => v._from._openid === this.userinfo._openid).length > 0) {
        this.commentMsg = '你已经评论过啦😄'
        return false
      }
      return true
    }
  },
  methods: {
    async _getDetail () { // 获取书籍详情
      await db
        .collection('books')
        .where({_id: this.bookId})
        .get()
        .then(res => {
          if (res.data.length > 0) {
            // this.bookInfo = res.data[0]
            this.bookInfo = Object.assign({}, res.data[0], {
              summary: res.data[0].summary.split('\n')
            })
            wx.setNavigationBarTitle({title: this.bookInfo.title})
            this.bookCountInc()
          } else {
            showMod({ // 提示框 点击确认返回上一页
              title: '错误',
              content: '未查询到该书，点击确定返回首页',
              success (confirm) {
                if (confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }
        })
    },
    bookCountInc () { // 书籍浏览信息加 1
      wx.cloud
        .callFunction({
          name: 'bookCountInc',
          data: {
            _id: this.bookId
          }
        })
        .then()
        .catch(err => {
          console.error(err)
        })
    },
    getGeo (e) { // 获取地理位置
      let url = 'https://api.map.baidu.com/geocoder/v2/?ak=7jS9nhFtIyqI7IvVmW3lTCSqPvZ9Skoy'
      if (e.target.value) {
        wx.getLocation({
          type: 'wgs84',
          altitude: false,
          success: (geo) => {
            wx.request({
              url,
              data: {
                location: `${geo.latitude},${geo.longitude}`,
                output: 'json'
              },
              success: (res) => {
                if (res.data.status === 0) {
                  this.location = res.data.result.addressComponent.city
                } else {
                  this.location = '未知'
                }
              }
            })
          }
        })
      } else {
        this.location = ''
      }
    },
    getPhone (e) { // 获取手机型号
      if (e.target.value) {
        this.phone = wx.getSystemInfoSync().model
      } else {
        this.phone = ''
      }
    },
    addComment () { // 提交评论
      // 评论内容 手机型号 地理位置 图书id 用户openid
      if (!this.comment) return
      const data = {
        comment: this.comment,
        location: this.location,
        phone: this.phone,
        bookid: this.bookId,
        _from: this.userinfo
      }
      wx.cloud.callFunction({
        name: 'addComment',
        data
      })
        .then(res => {
          if (res.result._id.length > 0) {
            showMod({
              title: '成功',
              content: '评论上传成功'
            })
            this.comment = ''
            this._getComments()
          }
        })
        .catch(err => console.error(err))
    },
    async _getComments () { // 获取本书评论数据
      await wx.cloud.callFunction({
        name: 'getComments',
        data: {
          bookid: this.bookId
        }
      })
        .then(res => {
          this.comments = res.result.data
          this.readyFor = true
        })
    }
  },
  mounted () {
    this.bookId = this.$root.$mp.query.id
    this.readyFor = false
    this._getDetail()

    this._getComments()
    const userinfo = wx.getStorageSync('__USER__')[0]
    if (userinfo) {
      this.userinfo = {
        _openid: userinfo._openid,
        avatarUrl: userinfo.avatarUrl,
        nickName: userinfo.nickName
      }
    }
    wx.showShareMenu()
  },
  components: {
    BookInfo,
    CommentList
  }
}
</script>

<style lang="stylus" scoped>
  .comments
    margin-top 10px
    .textarea
      width 730rpx
      height 200rpx
      background-color #eeeeee
      padding 10rpx
      font-size 14px
    .location
    .phone
      margin-top 10px
      padding 5px 10px
</style>
